import cloud from '@lafjs/cloud'
import { S3 } from '@aws-sdk/client-s3'
const fs = require('fs')
const env = process.env

const bucketName = 'file' // 不带 Laf 应用 appid
const Bucket = `dhkno3mf-${bucketName}`// 拼接文件桶名字

const s3Client = new S3({
  endpoint: env.OSS_EXTERNAL_ENDPOINT,
  region: env.OSS_REGION,
  credentials: {
    accessKeyId: env.OSS_ACCESS_KEY,
    secretAccessKey: env.OSS_ACCESS_SECRET,
  },
  forcePathStyle: true,
})

export default async function (ctx: FunctionContext) {
  let element = ctx.files[0]
  let { path, filename, mimetype, originalname } = element

  const data = await fs.readFileSync(path)

  await uploadAppFile(filename, data, mimetype)

  const bucket = cloud.storage.bucket(Bucket)
  const url = bucket.externalUrl(filename)  //永久访问链接

  add({ name: originalname, url })

  return cloud.utils.requestReturn({ data: url })
}

//新增到文件列表
async function add(params) {
  await cloud.utils.addData("file-list", params)
}

// 上传文件
async function uploadAppFile(Key: string, Body, ContentType) {
  const res = await s3Client.putObject({ Bucket, Key, ContentType, Body })
  return res
}

